package com.cfx.exercise_46;

import java.io.FileOutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

public class HeaderAndFooter extends PdfPageEventHelper{
	 public PdfTemplate tpl;  
     
	    public BaseFont bf;  
	public static void main(String[] args) throws Exception {
		
		Document doc = new Document();
		PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("pdf/123.pdf"));
		HeaderAndFooter event = new HeaderAndFooter();
		writer.setPageEvent(event);
		doc.open();
		Paragraph p = new Paragraph("测试文档");
		doc.add(p);
		doc.close();
	}
	public void onOpenDocument(PdfWriter writer, Document document) {
		 try {
		 tpl = writer.getDirectContent().createTemplate(100, 100);
		 bf = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED,true); 
		}
		 catch(Exception e) {
		 throw new ExceptionConverter(e);
		}
		}

		 public void onEndPage(PdfWriter writer, Document document) {
		//在每页结束的时候把“第x页”信息写道模版指定位置
		 PdfContentByte cb = writer.getDirectContent();
		cb.saveState();
		 String text ="第"+ writer.getPageNumber() +"页,共";
		cb.beginText();
		 cb.setFontAndSize(bf, 8);
		 cb.setTextMatrix(460, 786);//定位“第x页,共” 在具体的页面调试时候需要更改这xy的坐标
		cb.showText(text);
		cb.endText();
		 cb.addTemplate(tpl, 492, 786);//定位“y页” 在具体的页面调试时候需要更改这xy的坐标

		cb.saveState();
		cb.stroke();
		cb.restoreState();
		cb.closePath();//sanityCheck();
		System.out.println("11");
		}

		public void onCloseDocument(PdfWriter writer, Document document) {
		//关闭document的时候获取总页数，并把总页数按模版写道之前预留的位置
			 System.out.println("1");
		tpl.beginText();
		 tpl.setFontAndSize(bf, 8);
		 tpl.showText(Integer.toString(writer.getPageNumber() - 1)+"页");
		tpl.endText();
		tpl.closePath();//sanityCheck();
		System.out.println("2");
		}
}
